#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
共享认证依赖
"""

from fastapi import Request, HTTPException, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from src.database.database import get_async_db
from src.models.user import UserInfo
from src.service.user_service import UserService
from src.middlewares.jwt_middleware import get_current_user_from_request


async def get_current_user(
    request: Request,
    db: AsyncSession = Depends(get_async_db)
) -> UserInfo:
    """从中间件获取当前用户"""
    user_info = get_current_user_from_request(request)
    
    if not user_info:
        raise HTTPException(status_code=401, detail="无法获取用户信息")
    
    user_id = user_info.get("user_id")
    if not user_id:
        raise HTTPException(status_code=401, detail="无效的用户ID")
    
    # 从数据库获取完整用户信息
    user = await UserService.get_user_by_id(db, user_id)
    if user is None:
        raise HTTPException(status_code=401, detail="用户不存在")
    
    if user.status != 1:
        raise HTTPException(status_code=403, detail="用户已被禁用")
    
    return user


def get_client_ip(request: Request) -> str:
    """获取客户端IP地址"""
    # 优先从X-Forwarded-For获取（代理环境）
    forwarded_for = request.headers.get("X-Forwarded-For")
    if forwarded_for:
        # X-Forwarded-For可能包含多个IP，取第一个
        return forwarded_for.split(",")[0].strip()
    
    # 从X-Real-IP获取（Nginx代理）
    real_ip = request.headers.get("X-Real-IP")
    if real_ip:
        return real_ip.strip()
    
    # 直接连接的情况
    if request.client and request.client.host:
        return request.client.host
    
    return "unknown" 